package net.towee.model.group.impl;

import net.towee.model.account.AccountGroup;
import net.towee.model.account.ContactsGroup;
import net.towee.model.group.GroupIdentity;
import net.towee.server.persistence.impl.MongoDbStore;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Indexed;
import com.google.gwt.regexp.shared.RegExp;

/**
 * Implementation of group identity. Contain alias of group and printed name.
 * It's separated entity of basic group collection and it have the same id
 * that have GroupData of this group.
 * 
 * @author c58
 */
@Entity(MongoDbStore.GROUP_IDENTITY_COLLECTION)
public class GroupIdentityImpl implements GroupIdentity {
	@Id private String id;
	
	@Indexed(unique=true)
	private String alias;
	
	@Indexed(unique=true)
	private String name;
	
	public GroupIdentityImpl(){}
	public GroupIdentityImpl(String id){
		this.id = id;
	}
	public GroupIdentityImpl(String id, String alias, String name){
		this.id = id;
		this.setPrintName(name);
		this.setAlias(alias);
	}
	
	@Override
	public ContactsGroup toContactsGroup() {
		return null;
	}

	@Override
	public GroupIdentity toUsersGroup() {
		return this;
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public String getAlias() {
		return alias;
	}

	@Override
	public String getPrintName() {
		return name;
	}

	@Override
	public void setAlias(String name) {
		if(name != null)
			this.alias = RegExp.compile("[#!%?^]+","g").replace(name.trim(), "").replaceAll("\\s+", "_");
	}

	@Override
	public void setPrintName(String name) {
		if(name != null)
			this.name = name.trim();
	}
	
	@Override
	public boolean equals(Object o){
		if(o == this)
			return true;
		else if(o instanceof AccountGroup && ((AccountGroup)o).getGroupIdentity().getId().equals( getId() ) )
			return true;
		else if(o instanceof GroupIdentity && ((GroupIdentity)o).getId().equals( getId() ))
			return true;
		
		return false;
	}
	@Override
	public void setId(String string) {
		this.id = string;
	}
}
